% Copyright (C) 2017-2018 Titus Cieslewski, RPG, University of Zurich, 
%   Switzerland
%   You can contact the author at <titus at ifi dot uzh dot ch>
% Copyright (C) 2017-2018 Siddharth Choudhary, College of Computing,
%   Georgia Institute of Technology, Atlanta, GA, USA
% Copyright (C) 2017-2018 Davide Scaramuzza, RPG, University of Zurich, 
%   Switzerland
%
% This file is part of dslam_open.
%
% dslam_open is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% dslam_open is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with dslam_open. If not, see <http://www.gnu.org/licenses/>.

function decentr_state = setConvergedWhereApplicable(...
        updated_state, decentr_state)

n_robots = numel(decentr_state);
assert(numel(updated_state) == n_robots);

for robot_i = 1:n_robots
    if (isempty(updated_state{robot_i}))
        continue;
    end
    
    matched_frames = cellfun(@(x) ~isempty(x), ...
        decentr_state{robot_i}.place_matches);
    last_matched_frame = find(matched_frames, 1, 'last');
    
    if (isempty(last_matched_frame))
        continue;
    end
    
    last_updated_frame = numel(updated_state{robot_i}.Sim_O_C);
    
    if last_updated_frame >= last_matched_frame
        decentr_state{robot_i}.converged = true;
    end
end

end

